<?php

namespace apiend\modules\download\models;

use Yii;
use yii\db\Expression;
use yii\helpers\ArrayHelper;
use common\models\shop\ShopGoods;
use common\models\shop\ShopProduct;

/**
 * 店铺商品查询模型
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class GoodsSearch extends ShopGoods implements DownloadExportInterface {

    use DownloadExportTrait;

    /**
     * @var string 关键字
     */
    public $keyword;

    /**
     * @var string 关键字
     */
    public $filterStatus;

    /**
     * @inheritdoc
     */
    public function rules() {
        return [
            [['keyword', 'filterStatus', 'category_id', 'brand_id', 'store_id', 'status'], 'safe'],
        ];
    }

    /**
     * 绑定过滤条件
     * @param \common\db\ActiveQuery $query
     * @param string $alias
     */
    protected function buildQuery() {
        $query = static::find()->alias('sku')->active();
        $query->innerJoinWith('product t');
        $query->andWhere([
            't.deleted_at' => 0,
        ]);
        if ($this->store_id) {
            $query->with('store');
            $query->andWhere([
                't.store_id' => $this->store_id,
            ]);
        }
        if ($this->keyword) {
            $query->andFilterWhere([
                'or',
                ['like', 't.name', $this->keyword],
                ['like', 't.keyword', $this->keyword],
                ['like', 't.description', $this->keyword],
            ]);
        }
        if ($this->filterStatus) {
            if ($this->filterStatus == 'sale') {
                $query->andWhere([
                    't.status' => ShopProduct::STATUS_ACTIVE,
                ]);
            } elseif ($this->filterStatus == 'default') {
                $query->andWhere([
                    't.status' => [
                        ShopProduct::STATUS_DEFAULT,
                        ShopProduct::STATUS_OFFSHELF,
                    ],
                ]);
            } elseif ($this->filterStatus == 'pending') {
                $query->andWhere([
                    't.status' => [
                        ShopProduct::STATUS_LOCK,
                        ShopProduct::STATUS_AUDITING,
                    ],
                ]);
            } elseif ($this->filterStatus == 'reject') {
                $query->andWhere([
                    't.status' => ShopProduct::STATUS_REJECT,
                ]);
            } elseif ($this->filterStatus == 'forbid') {
                $query->andWhere([
                    't.status' => ShopProduct::STATUS_FORBID,
                ]);
            }
        }
        $orderBy = [
            't.id' => SORT_DESC,
            'sku.id' => SORT_DESC,
        ];
        if (!$this->store_id) {
            $orderBy = [
                't.store_id' => SORT_DESC,
                't.id' => SORT_DESC,
                'sku.id' => SORT_DESC,
            ];
        }
        $query->orderBy($orderBy);
        //$query->debug();
        return $query;
    }

    /**
     * 生成下载文件的名称
     * @return string
     */
    public function exportTitle() {
        return Yii::t('message', '{time}{name}', [
            'time' => date('Y年m月d日H:i:s'),
            'name' => '商品信息表',
        ]);
    }

    /**
     * 生成下载文件的名称
     * @return string
     */
    public function exportFileName($ext = true) {
        return Yii::t('message', '{time}-{title}{ext}', [
            'time' => date('Y年m月d日'),
            'title' => '商品信息表',
            'ext' => $ext ? '.csv' : '',
        ]);
    }

    public function exportCaptionOptions() {
        return [];
    }

    public function getStatusText() {
        if ($this->product && $this->product->status !== ShopProduct::STATUS_ACTIVE) {
            $markLabel = $this->product->getMarkLabel('status');
        } else {
            $markLabel = $this->getMarkLabel('status');
        }
        return $markLabel['label'];
    }

    /**
     * @inheritdoc
     */
    public function exportFields() {
        $fields = [
            'product_id:excelText',
            'id:excelText',
            'product.name',
            'name',
            'categoryMaster',
            'categoryParent',
            'category.name',
            'thumb',
            'goods_no:excelText',
            'stock',
            'sales',
            'lowstock',
            'weight',
            'volume',
            'min',
            'max_credit',
            'price',
            'market_price',
            'updated_at:datetime',
            'statusText',
        ];
        if (!$this->store_id) {
            $fields[] = 'store.name';
        }
        return $fields;
    }

    /**
     * {@inheritdoc}
     */
    public function attributeLabels() {
        return [
            'product_id' => '商品ID',
            'id' => 'SKUID',
            'product.name' => '商品名称',
            'name' => 'SKU名称',
            'categoryMaster' => '一级分类',
            'categoryParent' => '二级分类',
            'category.name' => '三级分类',
            'thumb' => '商品主图',
            'goods_no' => '商品编码',
            'stock' => '库存',
            'sales' => '销量',
            'lowstock' => '库存预警值',
            'weight' => '重量（g）',
            'volume' => '体积（cm³）',
            'min' => '起订数量',
            'max_credit' => '最大可用积分数量',
            'price' => '价格',
            'market_price' => '市场价',
            'updated_at' => '更新时间',
            'statusText' => '状态',
        ];
    }

}
